using System;

namespace XSResearch.Utilities
{
    public enum OperationType
    {
        XRConnection,
        DataProcessing,
        AgentCommunication
    }

    public class ErrorHandler
    {
        private readonly AppLogger _logger;
        private readonly int _maxRetries;

        public ErrorHandler(AppLogger logger, int maxRetries = 3)
        {
            _logger = logger;
            _maxRetries = maxRetries;
        }

        public T ExecuteWithRetry<T>(Func<T> operation, 
                                OperationType operationType,
                                string context = null)
        {
            int attempt = 0;
            while (true)
            {
                try
                {
                    return operation();
                }
                catch (Exception ex)
                {
                    attempt++;
                    LogError(ex, operationType, context, attempt);
                    
                    if (attempt >= _maxRetries)
                    {
                        throw new OperationFailedException(
                            "Operation failed after " + _maxRetries + " attempts", 
                            ex);
                    }
                }
            }
        }

        private void LogError(Exception ex, 
                            OperationType operationType,
                            string context,
                            int attempt)
        {
            _logger.Log("Attempt " + attempt + " failed for " + operationType + 
                      " (Context: " + (context ?? "N/A") + "): " + ex.Message, 
                       LogLevel.Error);
        }
    }

    public class OperationFailedException : Exception
    {
        public OperationFailedException(string message, Exception inner) 
            : base(message, inner) { }
    }
}